<?php
/**
 * 系统监控服务
 * 实现系统监控、性能监控、异常监控和告警功能
 */

declare(strict_types=1);

namespace app\service;

use think\facade\Db;
use think\facade\Log;
use think\facade\Cache;
use think\facade\Config;

class SystemMonitorService
{
    /**
     * 监控配置
     */
    private const MONITOR_CONFIG = [
        'check_interval' => 60,         // 检查间隔（秒）
        'alert_threshold' => [
            'cpu_usage' => 80,          // CPU使用率阈值
            'memory_usage' => 85,       // 内存使用率阈值
            'disk_usage' => 90,         // 磁盘使用率阈值
            'response_time' => 3000,    // 响应时间阈值（毫秒）
            'error_rate' => 5,          // 错误率阈值（%）
            'queue_size' => 1000,       // 队列积压阈值
        ],
        'alert_channels' => [
            'email' => true,
            'sms' => false,
            'webhook' => true,
            'database' => true
        ]
    ];

    /**
     * 监控指标类型
     */
    private const METRIC_TYPES = [
        'SYSTEM' => '系统指标',
        'APPLICATION' => '应用指标',
        'DATABASE' => '数据库指标',
        'API' => 'API指标',
        'SECURITY' => '安全指标',
        'BUSINESS' => '业务指标'
    ];

    /**
     * 告警级别
     */
    private const ALERT_LEVELS = [
        'INFO' => 1,      // 信息
        'WARNING' => 2,   // 警告
        'ERROR' => 3,     // 错误
        'CRITICAL' => 4   // 严重
    ];

    /**
     * 收集系统监控数据
     */
    public function collectSystemMetrics(): array
    {
        $metrics = [];
        
        try {
            // 1. 系统性能指标
            $systemMetrics = $this->getSystemPerformanceMetrics();
            $metrics['system'] = $systemMetrics;
            
            // 2. 应用性能指标
            $appMetrics = $this->getApplicationMetrics();
            $metrics['application'] = $appMetrics;
            
            // 3. 数据库性能指标
            $dbMetrics = $this->getDatabaseMetrics();
            $metrics['database'] = $dbMetrics;
            
            // 4. API性能指标
            $apiMetrics = $this->getApiMetrics();
            $metrics['api'] = $apiMetrics;
            
            // 5. 安全监控指标
            $securityMetrics = $this->getSecurityMetrics();
            $metrics['security'] = $securityMetrics;
            
            // 6. 业务监控指标
            $businessMetrics = $this->getBusinessMetrics();
            $metrics['business'] = $businessMetrics;
            
            // 存储监控数据
            $this->storeMetrics($metrics);
            
            // 检查告警条件
            $this->checkAlertConditions($metrics);
            
            return $metrics;
            
        } catch (\Exception $e) {
            Log::error('收集系统监控数据失败: ' . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 获取系统性能指标
     */
    private function getSystemPerformanceMetrics(): array
    {
        $metrics = [];
        
        try {
            // CPU使用率
            $cpuUsage = $this->getCpuUsage();
            $metrics['cpu_usage'] = $cpuUsage;
            
            // 内存使用率
            $memoryUsage = $this->getMemoryUsage();
            $metrics['memory_usage'] = $memoryUsage;
            
            // 磁盘使用率
            $diskUsage = $this->getDiskUsage();
            $metrics['disk_usage'] = $diskUsage;
            
            // 系统负载
            $loadAverage = $this->getLoadAverage();
            $metrics['load_average'] = $loadAverage;
            
            // 网络流量
            $networkStats = $this->getNetworkStats();
            $metrics['network'] = $networkStats;
            
        } catch (\Exception $e) {
            Log::warning('获取系统性能指标失败: ' . $e->getMessage());
        }
        
        return $metrics;
    }

    /**
     * 获取应用性能指标
     */
    private function getApplicationMetrics(): array
    {
        $metrics = [];
        
        try {
            // PHP进程状态
            $phpStatus = $this->getPhpProcessStatus();
            $metrics['php_status'] = $phpStatus;
            
            // 缓存命中率
            $cacheHitRate = $this->getCacheHitRate();
            $metrics['cache_hit_rate'] = $cacheHitRate;
            
            // 会话数量
            $sessionCount = $this->getActiveSessionCount();
            $metrics['active_sessions'] = $sessionCount;
            
            // 队列状态
            $queueStatus = $this->getQueueStatus();
            $metrics['queue_status'] = $queueStatus;
            
            // 错误日志统计
            $errorStats = $this->getErrorLogStats();
            $metrics['error_stats'] = $errorStats;
            
        } catch (\Exception $e) {
            Log::warning('获取应用性能指标失败: ' . $e->getMessage());
        }
        
        return $metrics;
    }

    /**
     * 获取数据库性能指标
     */
    private function getDatabaseMetrics(): array
    {
        $metrics = [];
        
        try {
            // 连接数统计
            $connectionStats = $this->getDatabaseConnectionStats();
            $metrics['connections'] = $connectionStats;
            
            // 查询性能
            $queryPerformance = $this->getQueryPerformanceStats();
            $metrics['query_performance'] = $queryPerformance;
            
            // 表大小统计
            $tableStats = $this->getTableSizeStats();
            $metrics['table_stats'] = $tableStats;
            
            // 慢查询统计
            $slowQueries = $this->getSlowQueryStats();
            $metrics['slow_queries'] = $slowQueries;
            
            // 数据库可用性
            $availability = $this->checkDatabaseAvailability();
            $metrics['availability'] = $availability;
            
        } catch (\Exception $e) {
            Log::warning('获取数据库性能指标失败: ' . $e->getMessage());
        }
        
        return $metrics;
    }

    /**
     * 获取API性能指标
     */
    private function getApiMetrics(): array
    {
        $metrics = [];
        
        try {
            // API请求统计
            $requestStats = $this->getApiRequestStats();
            $metrics['request_stats'] = $requestStats;
            
            // 响应时间统计
            $responseTimeStats = $this->getApiResponseTimeStats();
            $metrics['response_time'] = $responseTimeStats;
            
            // 错误率统计
            $errorRateStats = $this->getApiErrorRateStats();
            $metrics['error_rate'] = $errorRateStats;
            
            // 热门接口统计
            $popularEndpoints = $this->getPopularEndpoints();
            $metrics['popular_endpoints'] = $popularEndpoints;
            
        } catch (\Exception $e) {
            Log::warning('获取API性能指标失败: ' . $e->getMessage());
        }
        
        return $metrics;
    }

    /**
     * 获取安全监控指标
     */
    private function getSecurityMetrics(): array
    {
        $metrics = [];
        
        try {
            // 安全事件统计
            $securityEvents = $this->getSecurityEventStats();
            $metrics['security_events'] = $securityEvents;
            
            // 登录失败统计
            $loginFailures = $this->getLoginFailureStats();
            $metrics['login_failures'] = $loginFailures;
            
            // 异常访问统计
            $suspiciousAccess = $this->getSuspiciousAccessStats();
            $metrics['suspicious_access'] = $suspiciousAccess;
            
            // IP黑名单状态
            $blacklistStats = $this->getIpBlacklistStats();
            $metrics['ip_blacklist'] = $blacklistStats;
            
        } catch (\Exception $e) {
            Log::warning('获取安全监控指标失败: ' . $e->getMessage());
        }
        
        return $metrics;
    }

    /**
     * 获取业务监控指标
     */
    private function getBusinessMetrics(): array
    {
        $metrics = [];
        
        try {
            // 用户活跃度
            $userActivity = $this->getUserActivityStats();
            $metrics['user_activity'] = $userActivity;
            
            // 审批流程统计
            $workflowStats = $this->getWorkflowStats();
            $metrics['workflow_stats'] = $workflowStats;
            
            // 数据增长统计
            $dataGrowth = $this->getDataGrowthStats();
            $metrics['data_growth'] = $dataGrowth;
            
            // 功能使用统计
            $featureUsage = $this->getFeatureUsageStats();
            $metrics['feature_usage'] = $featureUsage;
            
        } catch (\Exception $e) {
            Log::warning('获取业务监控指标失败: ' . $e->getMessage());
        }
        
        return $metrics;
    }

    /**
     * 检查告警条件
     */
    private function checkAlertConditions(array $metrics): void
    {
        $alerts = [];
        
        // 1. 系统告警检查
        if (isset($metrics['system']['cpu_usage']) && 
            $metrics['system']['cpu_usage'] > self::MONITOR_CONFIG['alert_threshold']['cpu_usage']) {
            $alerts[] = [
                'type' => 'SYSTEM',
                'level' => self::ALERT_LEVELS['WARNING'],
                'message' => "CPU使用率过高: {$metrics['system']['cpu_usage']}%",
                'metric' => 'cpu_usage',
                'value' => $metrics['system']['cpu_usage'],
                'threshold' => self::MONITOR_CONFIG['alert_threshold']['cpu_usage']
            ];
        }
        
        if (isset($metrics['system']['memory_usage']) && 
            $metrics['system']['memory_usage'] > self::MONITOR_CONFIG['alert_threshold']['memory_usage']) {
            $alerts[] = [
                'type' => 'SYSTEM',
                'level' => self::ALERT_LEVELS['WARNING'],
                'message' => "内存使用率过高: {$metrics['system']['memory_usage']}%",
                'metric' => 'memory_usage',
                'value' => $metrics['system']['memory_usage'],
                'threshold' => self::MONITOR_CONFIG['alert_threshold']['memory_usage']
            ];
        }
        
        // 2. 数据库告警检查
        if (isset($metrics['database']['availability']) && !$metrics['database']['availability']) {
            $alerts[] = [
                'type' => 'DATABASE',
                'level' => self::ALERT_LEVELS['CRITICAL'],
                'message' => '数据库连接失败',
                'metric' => 'availability',
                'value' => false,
                'threshold' => true
            ];
        }
        
        // 3. API告警检查
        if (isset($metrics['api']['response_time']['avg']) && 
            $metrics['api']['response_time']['avg'] > self::MONITOR_CONFIG['alert_threshold']['response_time']) {
            $alerts[] = [
                'type' => 'API',
                'level' => self::ALERT_LEVELS['WARNING'],
                'message' => "API响应时间过长: {$metrics['api']['response_time']['avg']}ms",
                'metric' => 'response_time',
                'value' => $metrics['api']['response_time']['avg'],
                'threshold' => self::MONITOR_CONFIG['alert_threshold']['response_time']
            ];
        }
        
        // 4. 安全告警检查
        if (isset($metrics['security']['security_events']['high_risk_count']) && 
            $metrics['security']['security_events']['high_risk_count'] > 0) {
            $alerts[] = [
                'type' => 'SECURITY',
                'level' => self::ALERT_LEVELS['ERROR'],
                'message' => "检测到高风险安全事件: {$metrics['security']['security_events']['high_risk_count']} 个",
                'metric' => 'high_risk_events',
                'value' => $metrics['security']['security_events']['high_risk_count'],
                'threshold' => 0
            ];
        }
        
        // 发送告警
        if (!empty($alerts)) {
            $this->sendAlerts($alerts);
        }
    }

    /**
     * 发送告警
     */
    private function sendAlerts(array $alerts): void
    {
        foreach ($alerts as $alert) {
            try {
                // 1. 记录到数据库
                if (self::MONITOR_CONFIG['alert_channels']['database']) {
                    $this->storeAlert($alert);
                }
                
                // 2. 发送邮件告警
                if (self::MONITOR_CONFIG['alert_channels']['email']) {
                    $this->sendEmailAlert($alert);
                }
                
                // 3. 发送短信告警
                if (self::MONITOR_CONFIG['alert_channels']['sms']) {
                    $this->sendSmsAlert($alert);
                }
                
                // 4. 发送Webhook告警
                if (self::MONITOR_CONFIG['alert_channels']['webhook']) {
                    $this->sendWebhookAlert($alert);
                }
                
                Log::info('告警发送成功', $alert);
                
            } catch (\Exception $e) {
                Log::error('发送告警失败: ' . $e->getMessage(), $alert);
            }
        }
    }

    /**
     * 存储监控指标
     */
    private function storeMetrics(array $metrics): void
    {
        try {
            $currentTime = time();
            
            foreach ($metrics as $category => $categoryMetrics) {
                foreach ($categoryMetrics as $metric => $value) {
                    Db::name('system_monitor_metrics')->insert([
                        'category' => $category,
                        'metric_name' => $metric,
                        'metric_value' => is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value,
                        'collect_time' => $currentTime,
                        'create_time' => $currentTime
                    ]);
                }
            }
            
        } catch (\Exception $e) {
            Log::error('存储监控指标失败: ' . $e->getMessage());
        }
    }

    /**
     * 存储告警记录
     */
    private function storeAlert(array $alert): void
    {
        Db::name('system_alerts')->insert([
            'alert_type' => $alert['type'],
            'alert_level' => $alert['level'],
            'message' => $alert['message'],
            'metric_name' => $alert['metric'],
            'metric_value' => $alert['value'],
            'threshold_value' => $alert['threshold'],
            'status' => 'pending',
            'create_time' => time(),
            'update_time' => time()
        ]);
    }

    /**
     * 获取监控面板数据
     */
    public function getDashboardData(array $options = []): array
    {
        $timeRange = $options['time_range'] ?? 'hour'; // hour, day, week, month
        $category = $options['category'] ?? 'all';
        
        $timeCondition = $this->buildTimeCondition($timeRange);
        
        $dashboard = [];
        
        // 1. 实时指标
        $dashboard['realtime'] = $this->getRealtimeMetrics();
        
        // 2. 趋势数据
        $dashboard['trends'] = $this->getTrendData($timeCondition, $category);
        
        // 3. 告警统计
        $dashboard['alerts'] = $this->getAlertStats($timeCondition);
        
        // 4. 系统概览
        $dashboard['overview'] = $this->getSystemOverview();
        
        // 5. 热点分析
        $dashboard['hotspots'] = $this->getHotspotAnalysis($timeCondition);
        
        return $dashboard;
    }

    /**
     * 获取CPU使用率
     */
    private function getCpuUsage(): float
    {
        if (function_exists('sys_getloadavg')) {
            $load = sys_getloadavg();
            return round($load[0] * 100 / $this->getCpuCores(), 2);
        }
        return 0.0;
    }

    /**
     * 获取内存使用率
     */
    private function getMemoryUsage(): float
    {
        $memInfo = $this->getMemoryInfo();
        if ($memInfo['total'] > 0) {
            return round((($memInfo['total'] - $memInfo['available']) / $memInfo['total']) * 100, 2);
        }
        return 0.0;
    }

    /**
     * 获取磁盘使用率
     */
    private function getDiskUsage(): float
    {
        $totalSpace = disk_total_space('/');
        $freeSpace = disk_free_space('/');
        
        if ($totalSpace > 0) {
            return round((($totalSpace - $freeSpace) / $totalSpace) * 100, 2);
        }
        return 0.0;
    }

    /**
     * 获取数据库连接统计
     */
    private function getDatabaseConnectionStats(): array
    {
        try {
            $stats = Db::query("SHOW STATUS LIKE 'Threads_%'");
            $connectionStats = [];
            
            foreach ($stats as $stat) {
                $connectionStats[strtolower($stat['Variable_name'])] = (int)$stat['Value'];
            }
            
            return $connectionStats;
        } catch (\Exception $e) {
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * 检查数据库可用性
     */
    private function checkDatabaseAvailability(): bool
    {
        try {
            Db::query('SELECT 1');
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 获取API请求统计
     */
    private function getApiRequestStats(): array
    {
        $now = time();
        $oneHourAgo = $now - 3600;
        
        try {
            $stats = Db::name('api_access_log')
                ->where('create_time', '>=', $oneHourAgo)
                ->field('COUNT(*) as total_requests, 
                        AVG(response_time) as avg_response_time,
                        SUM(CASE WHEN response_code >= 400 THEN 1 ELSE 0 END) as error_count')
                ->find();
            
            return $stats ?: ['total_requests' => 0, 'avg_response_time' => 0, 'error_count' => 0];
        } catch (\Exception $e) {
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * 获取工作流统计
     */
    private function getWorkflowStats(): array
    {
        try {
            $stats = Db::name('workflow_approval')
                ->field('status, COUNT(*) as count')
                ->where('create_time', '>=', time() - 86400) // 最近24小时
                ->group('status')
                ->select()
                ->toArray();
            
            return $stats;
        } catch (\Exception $e) {
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * 发送邮件告警
     */
    private function sendEmailAlert(array $alert): void
    {
        // TODO: 实现邮件告警
        Log::info('邮件告警', $alert);
    }

    /**
     * 发送短信告警
     */
    private function sendSmsAlert(array $alert): void
    {
        // TODO: 实现短信告警
        Log::info('短信告警', $alert);
    }

    /**
     * 发送Webhook告警
     */
    private function sendWebhookAlert(array $alert): void
    {
        // TODO: 实现Webhook告警
        Log::info('Webhook告警', $alert);
    }

    /**
     * 获取CPU核心数
     */
    private function getCpuCores(): int
    {
        return (int)shell_exec('nproc') ?: 1;
    }

    /**
     * 获取内存信息
     */
    private function getMemoryInfo(): array
    {
        $memInfo = ['total' => 0, 'available' => 0];
        
        if (is_readable('/proc/meminfo')) {
            $memInfoContent = file_get_contents('/proc/meminfo');
            if (preg_match('/MemTotal:\s+(\d+)/', $memInfoContent, $matches)) {
                $memInfo['total'] = (int)$matches[1] * 1024;
            }
            if (preg_match('/MemAvailable:\s+(\d+)/', $memInfoContent, $matches)) {
                $memInfo['available'] = (int)$matches[1] * 1024;
            }
        }
        
        return $memInfo;
    }

    /**
     * 获取负载平均值
     */
    private function getLoadAverage(): array
    {
        if (function_exists('sys_getloadavg')) {
            return sys_getloadavg();
        }
        return [0, 0, 0];
    }

    /**
     * 获取网络统计
     */
    private function getNetworkStats(): array
    {
        // 简化实现
        return ['rx_bytes' => 0, 'tx_bytes' => 0];
    }

    /**
     * 获取PHP进程状态
     */
    private function getPhpProcessStatus(): array
    {
        return [
            'memory_usage' => memory_get_usage(true),
            'memory_peak' => memory_get_peak_usage(true),
            'uptime' => $_SERVER['REQUEST_TIME'] - $_SERVER['REQUEST_TIME']
        ];
    }

    /**
     * 获取缓存命中率
     */
    private function getCacheHitRate(): float
    {
        // 简化实现
        return 95.5;
    }

    /**
     * 获取活跃会话数
     */
    private function getActiveSessionCount(): int
    {
        // 简化实现
        return 50;
    }

    /**
     * 获取队列状态
     */
    private function getQueueStatus(): array
    {
        // 简化实现
        return ['pending' => 10, 'processing' => 2, 'failed' => 1];
    }

    /**
     * 获取错误日志统计
     */
    private function getErrorLogStats(): array
    {
        // 简化实现
        return ['error_count' => 5, 'warning_count' => 15];
    }

    /**
     * 获取查询性能统计
     */
    private function getQueryPerformanceStats(): array
    {
        try {
            // 获取慢查询信息
            $slowQueries = Db::query("SHOW VARIABLES LIKE 'slow_query_log'");
            $slowQueryTime = Db::query("SHOW VARIABLES LIKE 'long_query_time'");
            
            // 获取查询缓存信息
            $queryCache = Db::query("SHOW STATUS LIKE 'Qcache%'");
            
            // 获取查询执行统计
            $comSelect = Db::query("SHOW STATUS LIKE 'Com_select'");
            $comInsert = Db::query("SHOW STATUS LIKE 'Com_insert'");
            $comUpdate = Db::query("SHOW STATUS LIKE 'Com_update'");
            $comDelete = Db::query("SHOW STATUS LIKE 'Com_delete'");
            
            return [
                'slow_query_log' => $slowQueries[0]['Value'] ?? 'OFF',
                'long_query_time' => (float)($slowQueryTime[0]['Value'] ?? 10),
                'query_cache' => $queryCache,
                'com_select' => (int)($comSelect[0]['Value'] ?? 0),
                'com_insert' => (int)($comInsert[0]['Value'] ?? 0),
                'com_update' => (int)($comUpdate[0]['Value'] ?? 0),
                'com_delete' => (int)($comDelete[0]['Value'] ?? 0)
            ];
        } catch (\Exception $e) {
            Log::warning('获取查询性能统计失败: ' . $e->getMessage());
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * 获取表大小统计
     */
    private function getTableSizeStats(): array
    {
        try {
            // 获取所有表的大小信息
            $tableSizes = Db::query("SELECT 
                table_name AS 'table',
                ROUND(((data_length + index_length) / 1024 / 1024), 2) AS 'size_mb'
                FROM information_schema.tables 
                WHERE table_schema = DATABASE()
                ORDER BY (data_length + index_length) DESC");
            
            return $tableSizes;
        } catch (\Exception $e) {
            Log::warning('获取表大小统计失败: ' . $e->getMessage());
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * 获取慢查询统计
     */
    private function getSlowQueryStats(): array
    {
        try {
            // 检查慢查询日志是否开启
            $slowQueryLog = Db::query("SHOW VARIABLES LIKE 'slow_query_log'");
            $longQueryTime = Db::query("SHOW VARIABLES LIKE 'long_query_time'");
            
            // 获取慢查询数量
            $slowQueryCount = Db::query("SHOW GLOBAL STATUS LIKE 'Slow_queries'");
            
            return [
                'slow_query_log' => $slowQueryLog[0]['Value'] ?? 'OFF',
                'long_query_time' => (float)($longQueryTime[0]['Value'] ?? 10),
                'slow_query_count' => (int)($slowQueryCount[0]['Value'] ?? 0)
            ];
        } catch (\Exception $e) {
            Log::warning('获取慢查询统计失败: ' . $e->getMessage());
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * 获取API响应时间统计
     */
    private function getApiResponseTimeStats(): array
    {
        $now = time();
        $oneHourAgo = $now - 3600;
        
        try {
            $stats = Db::name('api_access_log')
                ->where('create_time', '>=', $oneHourAgo)
                ->field('AVG(response_time) as avg_response_time,
                        MIN(response_time) as min_response_time,
                        MAX(response_time) as max_response_time,
                        COUNT(*) as total_requests')
                ->find();
            
            return $stats ?: [
                'avg_response_time' => 0,
                'min_response_time' => 0,
                'max_response_time' => 0,
                'total_requests' => 0
            ];
        } catch (\Exception $e) {
            Log::warning('获取API响应时间统计失败: ' . $e->getMessage());
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * 获取API错误率统计
     */
    private function getApiErrorRateStats(): array
    {
        $now = time();
        $oneHourAgo = $now - 3600;
        
        try {
            $totalRequests = Db::name('api_access_log')
                ->where('create_time', '>=', $oneHourAgo)
                ->count();
            
            $errorRequests = Db::name('api_access_log')
                ->where('create_time', '>=', $oneHourAgo)
                ->where('response_code', '>=', 400)
                ->count();
            
            $errorRate = $totalRequests > 0 ? round(($errorRequests / $totalRequests) * 100, 2) : 0;
            
            return [
                'total_requests' => $totalRequests,
                'error_requests' => $errorRequests,
                'error_rate' => $errorRate
            ];
        } catch (\Exception $e) {
            Log::warning('获取API错误率统计失败: ' . $e->getMessage());
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * 获取热门接口统计
     */
    private function getPopularEndpoints(): array
    {
        $now = time();
        $oneDayAgo = $now - 86400;
        
        try {
            $popularEndpoints = Db::name('api_access_log')
                ->where('create_time', '>=', $oneDayAgo)
                ->field('endpoint, COUNT(*) as request_count')
                ->group('endpoint')
                ->order('request_count', 'desc')
                ->limit(10)
                ->select()
                ->toArray();
            
            return $popularEndpoints;
        } catch (\Exception $e) {
            Log::warning('获取热门接口统计失败: ' . $e->getMessage());
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * 获取安全事件统计
     */
    private function getSecurityEventStats(): array
    {
        $now = time();
        $oneDayAgo = $now - 86400;
        
        try {
            // 获取安全事件总数
            $totalEvents = Db::name('security_events')
                ->where('create_time', '>=', $oneDayAgo)
                ->count();
            
            // 获取高风险事件数
            $highRiskEvents = Db::name('security_events')
                ->where('create_time', '>=', $oneDayAgo)
                ->where('risk_level', 'high')
                ->count();
            
            // 获取中风险事件数
            $mediumRiskEvents = Db::name('security_events')
                ->where('create_time', '>=', $oneDayAgo)
                ->where('risk_level', 'medium')
                ->count();
            
            // 按类型分组统计
            $eventsByType = Db::name('security_events')
                ->where('create_time', '>=', $oneDayAgo)
                ->field('event_type, COUNT(*) as count')
                ->group('event_type')
                ->select()
                ->toArray();
            
            return [
                'total_events' => $totalEvents,
                'high_risk_count' => $highRiskEvents,
                'medium_risk_count' => $mediumRiskEvents,
                'events_by_type' => $eventsByType
            ];
        } catch (\Exception $e) {
            Log::warning('获取安全事件统计失败: ' . $e->getMessage());
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * 获取登录失败统计
     */
    private function getLoginFailureStats(): array
    {
        $now = time();
        $oneHourAgo = $now - 3600;
        
        try {
            // 获取登录失败次数
            $loginFailures = Db::name('login_logs')
                ->where('create_time', '>=', $oneHourAgo)
                ->where('status', 0) // 0表示登录失败
                ->count();
            
            // 获取失败的IP数
            $failedIps = Db::name('login_logs')
                ->where('create_time', '>=', $oneHourAgo)
                ->where('status', 0)
                ->distinct(true)
                ->field('ip_address')
                ->select()
                ->count();
            
            return [
                'failure_count' => $loginFailures,
                'failed_ips' => $failedIps
            ];
        } catch (\Exception $e) {
            Log::warning('获取登录失败统计失败: ' . $e->getMessage());
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * 获取异常访问统计
     */
    private function getSuspiciousAccessStats(): array
    {
        $now = time();
        $oneDayAgo = $now - 86400;
        
        try {
            // 获取异常访问次数
            $suspiciousAccessCount = Db::name('access_logs')
                ->where('create_time', '>=', $oneDayAgo)
                ->where('is_suspicious', 1)
                ->count();
            
            // 获取异常访问的IP数
            $suspiciousIps = Db::name('access_logs')
                ->where('create_time', '>=', $oneDayAgo)
                ->where('is_suspicious', 1)
                ->distinct(true)
                ->field('ip_address')
                ->select()
                ->count();
            
            return [
                'suspicious_count' => $suspiciousAccessCount,
                'suspicious_ips' => $suspiciousIps
            ];
        } catch (\Exception $e) {
            Log::warning('获取异常访问统计失败: ' . $e->getMessage());
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * 获取IP黑名单状态
     */
    private function getIpBlacklistStats(): array
    {
        try {
            // 获取黑名单IP总数
            $blacklistCount = Db::name('ip_blacklist')
                ->count();
            
            // 获取最近24小时新增的黑名单IP数
            $recentlyAdded = Db::name('ip_blacklist')
                ->where('create_time', '>=', time() - 86400)
                ->count();
            
            // 获取被拦截的请求次数
            $blockedRequests = Db::name('access_logs')
                ->where('is_blocked', 1)
                ->count();
            
            return [
                'total_blacklisted' => $blacklistCount,
                'recently_added' => $recentlyAdded,
                'blocked_requests' => $blockedRequests
            ];
        } catch (\Exception $e) {
            Log::warning('获取IP黑名单状态失败: ' . $e->getMessage());
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * 构建时间条件
     */
    private function buildTimeCondition(string $timeRange): array
    {
        $now = time();
        $timeMap = [
            'hour' => 3600,
            'day' => 86400,
            'week' => 604800,
            'month' => 2592000
        ];
        
        $seconds = $timeMap[$timeRange] ?? 3600;
        return ['create_time', '>=', $now - $seconds];
    }

    /**
     * 获取实时指标
     */
    private function getRealtimeMetrics(): array
    {
        return [
            'timestamp' => time(),
            'cpu_usage' => $this->getCpuUsage(),
            'memory_usage' => $this->getMemoryUsage(),
            'disk_usage' => $this->getDiskUsage(),
            'database_available' => $this->checkDatabaseAvailability()
        ];
    }

    /**
     * 获取趋势数据
     */
    private function getTrendData(array $timeCondition, string $category): array
    {
        // 简化实现
        return ['cpu_trend' => [], 'memory_trend' => [], 'api_trend' => []];
    }

    /**
     * 获取告警统计
     */
    private function getAlertStats(array $timeCondition): array
    {
        try {
            return Db::name('system_alerts')
                ->field('alert_level, COUNT(*) as count')
                ->where($timeCondition)
                ->group('alert_level')
                ->select()
                ->toArray();
        } catch (\Exception $e) {
            return [];
        }
    }

    /**
     * 获取系统概览
     */
    private function getSystemOverview(): array
    {
        return [
            'system_status' => 'healthy',
            'uptime' => '99.9%',
            'total_users' => 100,
            'active_users' => 25
        ];
    }

    /**
     * 获取热点分析
     */
    private function getHotspotAnalysis(array $timeCondition): array
    {
        return [
            'high_usage_apis' => [],
            'slow_queries' => [],
            'frequent_errors' => []
        ];
    }

    /**
     * 获取用户活跃度统计
     */
    private function getUserActivityStats(): array
    {
        try {
            $now = time();
            $oneDayAgo = $now - 86400;
            $oneWeekAgo = $now - 604800;
            
            // 日活跃用户数
            $dailyActiveUsers = Db::name('user_sessions')
                ->where('last_activity_time', '>=', $oneDayAgo)
                ->count();
            
            // 周活跃用户数
            $weeklyActiveUsers = Db::name('user_sessions')
                ->where('last_activity_time', '>=', $oneWeekAgo)
                ->count();
            
            // 在线用户数
            $onlineUsers = Db::name('user_sessions')
                ->where('last_activity_time', '>=', $now - 300) // 5分钟内活跃
                ->count();
            
            return [
                'daily_active_users' => $dailyActiveUsers,
                'weekly_active_users' => $weeklyActiveUsers,
                'online_users' => $onlineUsers,
                'timestamp' => $now
            ];
        } catch (\Exception $e) {
            Log::warning('获取用户活跃度统计失败: ' . $e->getMessage());
            return [
                'daily_active_users' => 0,
                'weekly_active_users' => 0,
                'online_users' => 0,
                'error' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取数据增长统计
     */
    private function getDataGrowthStats(): array
    {
        try {
            $now = time();
            $oneMonthAgo = $now - 2592000;
            
            // 用户增长
            $userGrowth = Db::name('users')
                ->where('create_time', '>=', $oneMonthAgo)
                ->count();
            
            // 订单增长
            $orderGrowth = Db::name('orders')
                ->where('create_time', '>=', $oneMonthAgo)
                ->count();
            
            return [
                'user_growth' => $userGrowth,
                'order_growth' => $orderGrowth,
                'timestamp' => $now
            ];
        } catch (\Exception $e) {
            Log::warning('获取数据增长统计失败: ' . $e->getMessage());
            return [
                'user_growth' => 0,
                'order_growth' => 0,
                'error' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取功能使用统计
     */
    private function getFeatureUsageStats(): array
    {
        try {
            $now = time();
            $oneMonthAgo = $now - 2592000;
            
            // 功能A使用次数
            $featureAUsage = Db::name('feature_usage')
                ->where('feature_name', 'feature_a')
                ->where('create_time', '>=', $oneMonthAgo)
                ->count();
            
            // 功能B使用次数
            $featureBUsage = Db::name('feature_usage')
                ->where('feature_name', 'feature_b')
                ->where('create_time', '>=', $oneMonthAgo)
                ->count();
            
            return [
                'feature_a_usage' => $featureAUsage,
                'feature_b_usage' => $featureBUsage,
                'timestamp' => $now
            ];
        } catch (\Exception $e) {
            Log::warning('获取功能使用统计失败: ' . $e->getMessage());
            return [
                'feature_a_usage' => 0,
                'feature_b_usage' => 0,
                'error' => $e->getMessage()
            ];
        }
    }
}